package com.tianqu.tms.www.rental.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.RentalLocationInfo;
import com.tianqu.tms.www.rental.actionform.RentalContractAddInputForm;
import com.tianqu.tms.www.rental.actionform.RentalLocationAddInputForm;
import com.tianqu.tms.www.rental.controller.RentalLocationListController;
import com.tianqu.tms.www.rental.viewhelper.RentalContractAddInputViewHelper;
import com.tianqu.tms.www.rental.viewhelper.RentalLocationViewHelper;

/**
 * 租位修改/删除 - 租位一览
 * @author mufeiyu
 *
 */
public class RentalLocationListAction extends TmsAction {

	private Logger logger = Logger.getLogger(RentalLocationListAction.class);
	
	public final static String PAGENO = "pageNo";
	public final static String SORTKEY = "sortKey";
	public final static String MAXINDEX = "maxIndex";
	public final static String ASC = "asc";
	public final static String DELETEFLG = "deleteFlg";
	
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext uc) throws Exception {
		
		logger.debug(this.getClass().getName() + "#execute was called.");

		RentalLocationViewHelper view = new RentalLocationViewHelper();
		if(uc.getAttribute(TmsConstants.VIEWHELP)!=null){
			uc.removeAttribute(TmsConstants.VIEWHELP);
		}
		
		if ("true".equals(uc.getAttribute(DELETEFLG))) {
			uc.removeAttribute(DELETEFLG);
		} else if(request.getParameter(PAGENO) == null) {
			
			uc.setAttribute(PAGENO, view.getPageNo());
			uc.setAttribute(SORTKEY, "7");
			uc.setAttribute(MAXINDEX, "20");
			uc.setAttribute(ASC, "true");
			
			RentalLocationAddInputForm rentalForm = (RentalLocationAddInputForm) uc.getInputForm();
			uc.setAttribute("seniorForm",rentalForm);
			
			// 租位编号
			view.setLocationSerial(rentalForm.getLocationSerial());
			
			// 租位类型
			Codes codes = Codes.getInstance();
			view.setRentalTypeList(convertRentalType(rentalForm.getStrRentalType()));
			
			// 租位状态
			List rentalStatusList = getRentalStatusList(rentalForm.getRentalStatus());
			view.setRentalStatusList(rentalStatusList);
			
			// 租位面积(㎡) / 区间		
			view.setAcreageS(rentalForm.getAcreageS());
			view.setAcreageE(rentalForm.getAcreageE());
			
			// 车位数量(个) / 区间
			view.setCarPortS(rentalForm.getCarPortS());
			view.setCarPortE(rentalForm.getCarPortE());
			
			// 租位区域
			List areaList = codes.getCodeslistByItemId(Codes.RENTAL_AREA);
			view.setRentalAreaList(areaList);
			view.setRentalArea(rentalForm.getRentalArea());
			
			// 登记日期 / 区间
			view.setUpdateTimeS(rentalForm.getUpdateTimeS());
			view.setUpdateTimeE(rentalForm.getUpdateTimeE());
			uc.setAttribute(TmsConstants.VIEWHELP, view);
			
			if ("1".equals(uc.getAttribute("searchFlg"))) {
				
				uc.removeAttribute("searchFlg");
				
				// 租位类型
				List rentalTypeList = codes.getCodeslistByItemId(Codes.RENTAL_TYPE);		
				String[] rentalType = rentalForm.getStrRentalType();
				
				// 租位状态
				String[] rentalStatus = rentalForm.getRentalStatus();
				
				if (StringUtil.isNullOrBlank(rentalForm.getLocationSerial())
						&& StringUtil.isNullOrBlank(rentalForm.getAcreageS()) && StringUtil.isNullOrBlank(rentalForm.getAcreageE()) 
						&& StringUtil.isNullOrBlank(rentalForm.getCarPortS()) && StringUtil.isNullOrBlank(rentalForm.getCarPortE()) 
						&& (null == rentalType || rentalType.length == 0 || rentalType.length == rentalTypeList.size())	
						&& (null == rentalStatus || rentalStatus.length == 0 || rentalStatus.length == 2
						&& rentalForm.getRentalArea() == 0)	
						&& StringUtil.isNullOrBlank(rentalForm.getUpdateTimeS()) && StringUtil.isNullOrBlank(rentalForm.getUpdateTimeE())) {
					
					setErrorsToRequest(request, TmsConstants.U0037, null); // 必须输入至少一个查询条件。
					uc.setAttribute("errFlg", "true");
				}
				
				if((StringUtil.isNotBlank(rentalForm.getAcreageS()) && !StringUtil.isNumeric(rentalForm.getAcreageS()))
						|| (StringUtil.isNotBlank(rentalForm.getAcreageE()) && !StringUtil.isNumeric(rentalForm.getAcreageE()))){
					
					String[] param = {"租位面积(㎡)/区间"};
					setErrorsToRequest(request, TmsConstants.U0015, param); 
					uc.setAttribute("errFlg", "true");
				}
				
				// 租位面积(㎡)/区间：【U0043】{0}填写的后一个数字不能比前一个数字小。
				if(StringUtil.isNotBlank(rentalForm.getAcreageS()) && StringUtil.isNotBlank(rentalForm.getAcreageE())
						 && Long.parseLong(rentalForm.getAcreageS()) > Long.parseLong(rentalForm.getAcreageE())){
					
					String[] param = {"租位面积(㎡)/区间"};
					setErrorsToRequest(request, TmsConstants.U0043, param); 
					uc.setAttribute("errFlg", "true");
				}
				
				if((StringUtil.isNotBlank(rentalForm.getCarPortS()) && !StringUtil.isNumeric(rentalForm.getCarPortS()))
						|| (StringUtil.isNotBlank(rentalForm.getCarPortE()) && !StringUtil.isNumeric(rentalForm.getCarPortE()))){
					
					String[] param = {"车位数量(个)/区间"};
					setErrorsToRequest(request, TmsConstants.U0015, param); 
					uc.setAttribute("errFlg", "true");

				}
				
				// 车位数量(个)/区间：【U0043】{0}填写的后一个数字不能比前一个数字小。
				if(StringUtil.isNotBlank(rentalForm.getCarPortS()) && StringUtil.isNotBlank(rentalForm.getCarPortE())
						 && Long.parseLong(rentalForm.getCarPortS()) > Long.parseLong(rentalForm.getCarPortE())){
					
					String[] param = {"车位数量(个)/区间"};
					setErrorsToRequest(request, TmsConstants.U0043, param); 
					uc.setAttribute("errFlg", "true");
				}
				
				//登记日期 / 区间check
				if ((!StringUtil.isNullOrBlank(rentalForm.getUpdateTimeS()))&&(!StringUtil.isNullOrBlank(rentalForm.getUpdateTimeE()))) {	
					SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
					//登记日期前段
					Date updateTimeS = formatDate.parse(rentalForm.getUpdateTimeS());
					//登记日期后端				
					Date updateTimeE = formatDate.parse(rentalForm.getUpdateTimeE());
					// 比较
					if (updateTimeE.compareTo(updateTimeS) < 0) {
						String[] param = {"登记日期/区间"};
						setErrorsToRequest(request, TmsConstants.U0038, param); //登记日期 / 区间填写的后一个日期不能比前一个日期小。
						uc.setAttribute("errFlg", "true");
					}
				}
							
				if ("true".equals(uc.getAttribute("errFlg"))) {
					return mapping.getInputForward();
				}
			}else {
				uc.setAttribute(PAGENO, uc.getAttribute(PAGENO));
				uc.setAttribute(SORTKEY, uc.getAttribute(SORTKEY));
				uc.setAttribute(MAXINDEX, uc.getAttribute(MAXINDEX));
				uc.setAttribute(ASC, uc.getAttribute(ASC));
			}
			
		}else {
		
			uc.setAttribute(PAGENO, request.getParameter(PAGENO));
			uc.setAttribute(SORTKEY, request.getParameter(SORTKEY));
			uc.setAttribute(MAXINDEX, request.getParameter(MAXINDEX));
			uc.setAttribute(ASC, request.getParameter(ASC));
		}
		
		RentalLocationListController controller = new RentalLocationListController();
		controller.execute(uc);

		List<RentalLocationViewHelper> view1 = (List<RentalLocationViewHelper>)uc.getAttribute(TmsConstants.VIEWHELP);
		
		if (view1 == null || view1.size() == 0) {//结果为空
			uc.setAttribute(TmsConstants.VIEWHELP, view);
			setErrorsToRequest(request, TmsConstants.U0039, null);
			uc.setAttribute("errFlg", "true");
			return mapping.getInputForward();
		}

		view.setList((List)uc.getAttribute(TmsConstants.VIEWHELP));
		RentalLocationInfo rentalLocationInfo = (RentalLocationInfo)uc.getAttribute(RentalLocationListController.PAGING);
		
		// viewhelp中设置翻页。
		view.setPageNo(Integer.toString(rentalLocationInfo.getPageNo()));
		view.setMaxIndex(Integer.toString(rentalLocationInfo.getMaxIndex()));
		view.setAsc(Boolean.toString(rentalLocationInfo.isAsc()));
		view.setSortKey(Integer.toString(rentalLocationInfo.getSortKey()));
		view.setTotalCount(Integer.toString(rentalLocationInfo.getTotalCount()));
		view.setDateFrom(Integer.toString(rentalLocationInfo.getDateFrom()));
		view.setDateTo(Integer.toString(rentalLocationInfo.getDateTo()));

		request.setAttribute(TmsConstants.VIEWHELP,view);
		uc.setAttribute(TmsConstants.VIEWHELP, view);
		
		
		logger.debug(this.getClass().getName() + "#execute was completed.");
		return mapping.findForward(TmsConstants.SUCCESS);
	}
	
	private List convertRentalType(String[] RentalType) throws TmsDaoException{
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		if(null != RentalType && RentalType.length > 0){
			for (int i = 0; i < RentalType.length; i++){
				int itemCode = StringUtils.isNumeric(RentalType[i])?Integer.parseInt(RentalType[i]):-1;
				map.put(itemCode, itemCode);
			}
		}
		List codeslist = Codes.getInstance().getCodeslistByItemId(Codes.RENTAL_TYPE);
		for (Object object : codeslist) {
			String checked = "";
			HashMap codesMap = (HashMap)object;
			if(map.get(codesMap.get("itemCode"))!=null ) checked = "checked";
			codesMap.put("checked", checked);
		}
		return codeslist;
	}

	public  List getRentalStatusList(String[] rentalStatus) {
		Map map = null;// 用于存储itemCode和itemValue
		List list = new ArrayList();
		
		map = new HashMap();
		map.put("itemCode", 1);
		map.put("itemValue", "已出租");
		
		if (null != rentalStatus && rentalStatus.length > 0) {
			for (int i = 0; i < rentalStatus.length; i++) {
				if ("1".equals(rentalStatus[i])) map.put("checked", "checked");
			}
		}

		list.add(map);
		
		map = new HashMap();
		map.put("itemCode", 2);
		map.put("itemValue", "未出租");
		
		if (null != rentalStatus && rentalStatus.length > 0) {
			for (int i = 0; i < rentalStatus.length; i++) {
				if ("2".equals(rentalStatus[i])) map.put("checked", "checked");
			}
		}
		
		list.add(map);
		
		if (list.size()==0) {
			return null;
		}		

		return list;
	}
}
